//
//  AppDelegate.swift
//  swift_demo_weibo
//
//  Created by 杨兵 on 15/5/10.
//  Copyright (c) 2015年 bing. All rights reserved.
//

import UIKit

// 添加常量作为view切换的通知常量
let viewControllerNotifi = "viewControllerNotifi"
// 全局常量,作为数据共享
var userInfoShared = UserAccount.loadUserAccount()

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        
        // 设置后台抓取数据时间为------最短时间
        application.setMinimumBackgroundFetchInterval(UIApplicationBackgroundFetchIntervalMinimum)
        var viewname = "Main"
        
        // 是否登陆
        if userInfoShared != nil {
            // 如果是新版本,跳到新特性
            if isNewVersion() {
                viewname = "NewFeature"
            } else {
                // 不是新版本跳到主页面
                viewname = "Welcome"
            }
        }
        switchViewController(viewname)
        
        // 注册通知
        notificationregist()
        
        // 注册视图切换通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "switchRootViewController:", name: viewControllerNotifi, object: nil)
        
        // 打开数据连接
        SQLiteManager.sharedSQLiteManager().openDB("Status.db")
        StatusDAL.createTable()
        
        
        
        window?.makeKeyAndVisible()
        
        // 设置导航文字的颜色
        setNavbackgrond()
        return true
    }
    
    
    // 注册通知授权
    private func notificationregist() {
        let notifType = UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound
        let settings = UIUserNotificationSettings(forTypes: notifType, categories: nil)
        UIApplication.sharedApplication().registerUserNotificationSettings(settings)
    }
    
    
    // 实现后台通知方法
    func application(application: UIApplication, performFetchWithCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
        
        Status.unreadMsg { (count) -> () in
            if count > 0 {
                completionHandler(UIBackgroundFetchResult.NewData)
                return
            }
            completionHandler(UIBackgroundFetchResult.NoData)
        }
    }
    
    
    
    // 通知切换控制器
    func switchRootViewController(obj: NSNotification){
        switchViewController(obj.object as! String)
    }
    
    // 检查登陆是否是新版本
    func isNewVersion() -> Bool{
        let versionKey = "versionKey"
        let currentVersion = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
        let cVersion = NSNumberFormatter().numberFromString(currentVersion)?.doubleValue ?? 0.0
        
        let boxV = NSUserDefaults.standardUserDefaults()
        let boxVersion = boxV.doubleForKey(versionKey)
        
        // 同步当前版本到沙盒
        boxV.setObject(currentVersion, forKey: versionKey)
        boxV.synchronize()

        return cVersion > boxVersion
    }
    
    
    // 切换视图
    func switchViewController(vi:String) {
        let sb = UIStoryboard(name: vi, bundle: nil)
        window?.rootViewController = sb.instantiateInitialViewController() as? UIViewController
    }
    
    
    
    
    func setNavbackgrond() {
        UINavigationBar.appearance().tintColor = UIColor.orangeColor()
        UITabBar.appearance().tintColor = UIColor.orangeColor()
    }


    
    // 进入后台后,刷新数据库数据,删除过期数据
    func applicationDidEnterBackground(application: UIApplication) {
        StatusDAL.clearCache()
    }
}

